﻿using System.IO.Pipes;
using System.Security.Principal;
using System.Threading.Tasks;
using Benchmark.Core.Communication.Data.Interface;
using Benchmark.Core.Communication.Data.Stream_Manager;

namespace Benchmark.Core.Communication.Hub.Impl.Pipe.Core
{
    public class PipeClient
    {
        public delegate void OnOperationCompletion();

        public OnOperationCompletion OnOperationComp;
        public string Pipename { get; set; }

        public byte[] BytesRead { get; set; }
        private IStreamManager _streamManager;
        public string ServerName { get; set; }
        public int TotalNumberofClients { get; set; }

        public void Connect(bool useServerStream = false)
        {



            if (useServerStream)
            {
                var clientStream = new NamedPipeServerStream(Pipename, PipeDirection.InOut, 1);
                _streamManager = new PipeStreamManager(clientStream);
                clientStream.WaitForConnection();
            }

            else
            {
                var clientStream = new NamedPipeClientStream(ServerName, Pipename, PipeDirection.InOut, PipeOptions.None,
                    TokenImpersonationLevel.Impersonation);
                _streamManager = new PipeStreamManager(clientStream);
                clientStream.Connect();
            }


        }

        public void Relenquish()
        {



        }


        protected void WriteAsyn(byte[] bytesToWrite)
        {

            Task.Factory.StartNew(() =>
            {
                _streamManager.WriteByte(bytesToWrite);
            }, TaskCreationOptions.PreferFairness);

        }


        protected void Write(byte[] bytesToWrite)
        {
            _streamManager.WriteByte(bytesToWrite);

        }


        protected byte[] ReadAsyn()
        {
            byte[] bytesRead = null;
            Task.Factory.StartNew(() =>
            {
                bytesRead = _streamManager.ReadByte();
            }, TaskCreationOptions.PreferFairness);

            return (bytesRead);

        }

        protected byte[] Read()
        {
            byte[] bytesRead = null;
            bytesRead = _streamManager.ReadByte();
            return (bytesRead);
        }

    }
}

